<?php
declare (strict_types=1);

namespace app\admin\controller\advertiser;

use app\admin\model\advertiser\AdvertiserThird as AdvertiserThirdModel;
use app\admin\model\base\UserOfficial;
use app\admin\model\base\UserProgram;
use app\BaseController;
use think\facade\Request;
use think\response\Json;

/**
 * 聚合平台管理
 */
class AdvertiserThird extends BaseController
{

    /**
     * 系聚合平台列表
     * @return Json
     */
    public function thirdList(): Json
    {
        $params['page'] = Request::param('page/d', 1);
        $params['limit'] = Request::param('limit/d', 10);
        $data = AdvertiserThirdModel::getList([], $params['page'], $params['limit']);
        return jsonReturn(1, $data);
    }

    /**
     * 聚合平台编辑
     * @return Json
     */
    public function thirdEdit(): Json
    {
        //公共参数
        $third_id = Request::param('id/d', 0);
        $params['enable'] = Request::param('enable/d', 0);
        $params['prohibit'] = Request::param('prohibit/a', []);
        $params['remark'] = Request::param('remark/s', '');
        //推广小程序
        $params['mini_name'] = Request::param('mini_name/s', '');
        $params['mini_ogh'] = Request::param('mini_ogh/s', '');
        $params['mini_appid'] = Request::param('mini_appid/s', '');
        $params['mini_link'] = Request::param('mini_link/s', '');
        //查看是否存在
        $model = AdvertiserThirdModel::where(['id' => $third_id])->find();
        if (!$model) {
            return jsonReturn(0, [], '操作对象不存在');
        }
        //处理参数
        $params['prohibit'] = json_encode(array_unique($params['prohibit']));
        $params['update_time'] = time();
        //写入数据库
        $res = $model->save($params);
        if ($res) {
            return jsonReturn(1, [], '修改成功');
        }
        return jsonReturn(0, [], '修改失败');
    }

    /**
     * 聚合平台统计
     * @return Json
     */
    public function thirdStatistics(): Json
    {
        $third_id = Request::param('third_id/d', 0);
        $page = Request::param('page/d', 1);
        $limit = Request::param('limit/d', 10);
        //查询是否存在
        $third = AdvertiserThirdModel::findOne(['id' => $third_id]);
        if (!$third) {
            return jsonReturn(0, []);
        }
        //生成对应的模型
        $LogModel = $third['type'] == 'OfficialAccount' ? new UserOfficial() : new UserProgram();
        //生成对应的日期
        $data = [];
        for ($i = 0; $i < $limit; $i++) {
            $t = time() - ($i * 86400) - (($page - 1) * $limit * 86400);
            $data[$i]['date'] = date('Y-m-d', $t);
            //查询数据库
            $data[$i]['count'] = $LogModel::where(['third_id' => $third_id])->whereDay('create_time', $data[$i]['date'])->count();
        }
        //返回参数
        $return = [
            'total' => 365,
            'per_page' => $limit,
            'current_page' => $page,
            'last_page' => intval(ceil(365 / $limit)),
            'data' => $data,
        ];
        return jsonReturn(1, $return);
    }


}
